package com.example.lotterysystem.controller;

import com.example.lotterysystem.common.errorcode.ControllerErrorCodeConstants;
import com.example.lotterysystem.common.exception.ControllerException;
import com.example.lotterysystem.common.exception.ServiceException;
import com.example.lotterysystem.common.pojo.CommonResult;
import com.example.lotterysystem.common.utils.JWTUtil;
import com.example.lotterysystem.common.utils.JacksonUtil;
import com.example.lotterysystem.controller.param.CreateActivityParam;
import com.example.lotterysystem.controller.param.PageParam;
import com.example.lotterysystem.controller.result.ActivityDetailResult;
import com.example.lotterysystem.controller.result.CreateActivityResult;
import com.example.lotterysystem.controller.result.SelectActivityList;
import com.example.lotterysystem.controller.result.SelectPrizeList;
import com.example.lotterysystem.service.IActivityService;
import com.example.lotterysystem.service.dto.ActivityDTO;
import com.example.lotterysystem.service.dto.ActivityDetailDTO;
import com.example.lotterysystem.service.dto.CreateActivityDTO;
import com.example.lotterysystem.service.dto.PageListDTO;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.stream.Collectors;

/**
 * 功能描述:
 *
 * @author Lenovo
 * @date 2025/1/31
 */
@Slf4j
@RestController
public class ActivityController {
    @Resource
    private IActivityService activityService;

    /**
     * 创建活动
     *
     * @param param
     * @return
     */
    @RequestMapping("/activity/create")
    public CommonResult<CreateActivityResult> createActivity(
            HttpServletRequest request,
            @Validated @RequestBody CreateActivityParam param) {
        log.info("createActivity 接收到参数：{}", JacksonUtil.writeValueAsString(param));
        String userToken = request.getHeader("user_token");
        Integer userId = JWTUtil.getUserIdFromToken(userToken);
        return CommonResult.success(convertToCreateActivityResult
                (activityService.createActivity(userId,param)));
    }

    private CreateActivityResult convertToCreateActivityResult(CreateActivityDTO createActivityDTO) {
        if (createActivityDTO == null) {
            throw new ControllerException(ControllerErrorCodeConstants.CREATE_ACTIVITY_ERROR);
        }
        CreateActivityResult result = new CreateActivityResult();
        result.setActivityId(createActivityDTO.getActivityId());
        return result;
    }

    /**
     * 获取活动列表
     * @param request
     * @param param
     * @return
     */
    @RequestMapping("/activity/find-list")
    public CommonResult<SelectActivityList> selectActivityByPage(HttpServletRequest request,
                                                                             PageParam param) {
        log.info("selectActivity接收到参数：{}", JacksonUtil.writeValueAsString(param));
        String userToken = request.getHeader("user_token");
        Integer userId = JWTUtil.getUserIdFromToken(userToken);

        PageListDTO<ActivityDTO> activityDTOPageListDTO = activityService.selectActivityByPage(userId,param);
        return CommonResult.success(convertToSelectActivityList(activityDTOPageListDTO));
    }

    /**
     * 查看活动详情
     * @param activityId
     * @return
     */
    @RequestMapping("/activity-detail/find")
    public CommonResult<ActivityDetailResult> getActivityDetail(Long activityId) {
        log.info("getActivityDetail接收到参数：{}", activityId);
        ActivityDetailDTO activityDetailDTO = activityService.selectActivityDetail(activityId);
        return CommonResult.success(convertToActivityDetailResult(activityDetailDTO));
    }

    private ActivityDetailResult convertToActivityDetailResult(ActivityDetailDTO activityDetailDTO) {
        if (activityDetailDTO == null) {
            throw new ControllerException(ControllerErrorCodeConstants.GET_ACTIVITY_DETAIL_ERROR);
        }
        ActivityDetailResult result = new ActivityDetailResult();
        result.setActivityId(activityDetailDTO.getActivityId());
        result.setActivityName(activityDetailDTO.getActivityName());
        result.setDescription(activityDetailDTO.getDesc());
        result.setValid(activityDetailDTO.valid());
        //抽奖顺序
        result.setPrizes(activityDetailDTO.getPrizeDTOList()
                .stream()
                .sorted(Comparator.comparingInt(prizeDTO -> prizeDTO.getTiers().getCode()))
                .map(prizeDTO -> {
                    ActivityDetailResult.Prize prize = new ActivityDetailResult.Prize();
                    prize.setPrizeId(prizeDTO.getPrizeId());
                    prize.setName(prizeDTO.getName());
                    prize.setImageUrl(prizeDTO.getImageUrl());
                    prize.setPrice(prizeDTO.getPrice());
                    prize.setDescription(prizeDTO.getDescription());
                    prize.setPrizeTierName(prizeDTO.getTiers().getMessage());
                    prize.setPrizeAmount(prizeDTO.getPrizeAmount());
                    prize.setValid(prizeDTO.valid());
                    return prize;
                }).collect(Collectors.toList())
        );
        result.setUsers(activityDetailDTO.getUserDTOList()
                .stream()
                .map(userDTO -> {
                    ActivityDetailResult.User user = new ActivityDetailResult.User();
                    user.setUserId(userDTO.getUserId());
                    user.setUserName(userDTO.getUserName());
                    user.setValid(userDTO.valid());
                    return user;
                }).collect(Collectors.toList())
        );
        return result;
    }

    private SelectActivityList convertToSelectActivityList(PageListDTO<ActivityDTO> activityList) {
        if (activityList == null) {
            throw new ServiceException(ControllerErrorCodeConstants.FIND_ACTIVITY_LIST_ERROR);
        }
        SelectActivityList result = new SelectActivityList();
        result.setTotal(activityList.getTotal());
        result.setRecords(activityList.getRecords()
                .stream()
                .map(activityDTO -> {
                    SelectActivityList.ActivityInfo activityInfo = new SelectActivityList.ActivityInfo();
                    activityInfo.setActivityId(activityDTO.getActivityId());
                    activityInfo.setActivityName(activityDTO.getActivityName());
                    activityInfo.setDescription(activityDTO.getDescription());
                    activityInfo.setValid(activityDTO.isValid());
                    return activityInfo;
                }).collect(Collectors.toList())
        );
        return result;
    }
}
